package com.newbee.activity;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.hhu.newbee.R;
import com.hhu.newbee.R.id;
import com.newbee.activity.tab.MainActivity;
import com.newbee.app.AppConfig;
import com.newbee.app.OnRefrushActivity;
import com.newbee.app.SpeechApp;
import com.newbee.service.MainService;
import com.newbee.service.MainServiceKey;
import com.newbee.service.MainServiceTask;
import com.newbee.service.TaskType;
import com.newbee.sound.Sound;
import com.tencent.connect.share.QQShare;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

public class VoiceAfterTransActivity extends Activity implements
		OnRefrushActivity, OnClickListener, IUiListener
{

	public static final String VOICE_FILE_NAME = "FILENAME";

	public static final String DATE = "DATE";

	public static final String TYPE = "TYPE";
	private TextView mTimeTextView;
	private EditText mContentTextView;

	private String fileName;

	private ProgressDialog mProgressDialog;

	// ForegroundColorSpan 为文字前景色，BackgroundColorSpan为文字背景色
	private File file;

	private Tencent QQ;

	private View alertMenu;

	private int mLuyinType;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.activity_voice_recg_edit);
		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		initLayout();
		initDates();

		file = new File(Sound.DIR + fileName.split("\\.")[0] + ".vtf");

		String content;
		StringBuffer sb = new StringBuffer("");
		initProgressDialog();
		this.findViewById(id.voice_trans_save).setOnClickListener(this);

		this.findViewById(R.id.alert_menu_check).setOnClickListener(this);

		if (file.exists())
		{

			try
			{
				BufferedReader br = new BufferedReader(new FileReader(file));
				while (null != (content = br.readLine()))
				{
					sb.append(content);
				}
				br.close();
				// mContentTextView.setText(jsonBuilder(sb.toString()));
				mContentTextView.setText(sb.toString());

			}
			catch (FileNotFoundException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			catch (IOException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
		else
		{
			sendMsg();
			this.mProgressDialog.setMessage("正在拼命为您转换     ╥﹏╥...");
			this.mProgressDialog.show();
		}
		this.findViewById(R.id.trans_avter_btn_back).setOnClickListener(this);

		this.findViewById(R.id.alert_menu_sendtofriend)
				.setOnClickListener(this);
		this.findViewById(R.id.alert_menu_save).setOnClickListener(this);
		initQQ();
	}

	private void initQQ()
	{

		QQ = Tencent.createInstance(SpeechApp.TENCENT_QQ_APPID,
				this.getApplicationContext());

	}

	private void ShareToQQ(String url)
	{
		final Bundle params = new Bundle();
		params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE,
				QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
		params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, url);
		params.putString(QQShare.SHARE_TO_QQ_TITLE, "语音小助手 文件分享");
		params.putString(QQShare.SHARE_TO_QQ_SUMMARY, "摘要:"
				+ mContentTextView.getText().toString().substring(0, 3) + "……");
		params.putString(QQShare.SHARE_TO_QQ_EXT_STR, mContentTextView
				.getText().toString());

		params.putString(QQShare.SHARE_TO_QQ_APP_NAME, "测试应用222222");
		QQ.shareToQQ(this, params, this);
	}

	private void initProgressDialog()
	{

		this.mProgressDialog = new ProgressDialog(this);
		this.mProgressDialog.setCancelable(false);
		this.mProgressDialog.setTitle("请稍等");
		this.mProgressDialog.setMessage("正在拼命为您转换     ╥﹏╥...");

	}

	private void initDates()
	{

		Bundle bundle = getIntent().getExtras();

		this.fileName = bundle.getString(VOICE_FILE_NAME);
		mTimeTextView.setText(bundle.getString(DATE));

		this.mLuyinType = bundle.getInt(TYPE);

	}

	private void sendMsg()
	{
		Map<String, Object> paras = new HashMap<String, Object>();
		paras.put(MainServiceKey.SINGLE_FILE_NAME, this.fileName);

		paras.put(MainServiceKey.LANG_TYPE, mLuyinType);

		MainServiceTask mst = new MainServiceTask(TaskType.SINGLE_VOICE_RECOG,
				paras, VoiceAfterTransActivity.class.getName());
		MainService.addActivityMap(VoiceAfterTransActivity.class.getName(),
				this);

		MainService.addTaskQueue(mst);
	}

	private void initLayout()
	{
		mTimeTextView = (TextView) this.findViewById(R.id.edit_content_time);
		mContentTextView = (EditText) this
				.findViewById(R.id.edit_content_textview);
		alertMenu = this.findViewById(R.id.alert_menu);
		alertMenu.setOnClickListener(this);
		this.findViewById(R.id.alert_menu_qq).setOnClickListener(this);

	}

	@Override
	protected void onDestroy()
	{

		if (mProgressDialog != null)
		{
			mProgressDialog.dismiss();
		}
		MainService.removeActivity(VoiceAfterTransActivity.class.getName());
		super.onDestroy();
	}

	@Override
	public void init()
	{
		// TODO Auto-generated method stub

	}

	@Override
	public RtInfo refresh(int taskID, Object... paras)
	{
		switch (taskID)
		{
		case TaskType.SINGLE_VOICE_RECOG:
		{
			String reString = (String) paras[0];
			this.mProgressDialog.hide();

			if (mLuyinType == VoiceSpeachActivity.EN && reString != null
					&& reString.length() == 2)
			{
				Toast.makeText(this, "请标准发音(づ￣3￣)づ╭❤～", Toast.LENGTH_LONG)
						.show();
				break;
			}
			else if (reString != null && reString.length() == 2)
			{
				Toast.makeText(this, "您好像没有说话哦(づ￣3￣)づ╭❤～", Toast.LENGTH_LONG)
						.show();
				break;
			}

			this.mContentTextView.setText(reString);
			try
			{
				BufferedWriter bw = new BufferedWriter(new FileWriter(new File(
						Sound.DIR + fileName.split("\\.")[0] + ".vtf")));
				bw.write(this.mContentTextView.getText().toString());
				bw.flush();
				bw.close();
			}
			catch (IOException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			break;

		}
		case TaskType.BEFORE_SHARE_QQ:
		{

			String fileName = (String) paras[0];

			if (fileName != null)
			{

				fileName = fileName.substring(1, fileName.length() - 1);

				ShareToQQ(AppConfig.HTTP_QQ_FILE + fileName);

			}
			else
			{
				Toast.makeText(this, "分享到QQ发生错误，请重试", Toast.LENGTH_LONG).show();
			}
			break;
		}
		case TaskType.CHECK_SPELL:
		{
			String reString = (String) paras[0];
			this.mProgressDialog.hide();
			SpannableStringBuilder builder = jsonBuilder(reString);
			this.mContentTextView.setText(builder);
			Toast.makeText(this, "文本校验完成！", Toast.LENGTH_LONG).show();
			if (this.mContentTextView.getText().toString().length() == 0)
			{
				Toast.makeText(this, "您好像没有说话哦。", Toast.LENGTH_LONG).show();
			}
			try
			{
				BufferedWriter bw = new BufferedWriter(new FileWriter(new File(
						Sound.DIR + fileName.split("\\.")[0] + ".vtf")));
				bw.write(this.mContentTextView.getText().toString());
				bw.flush();
				bw.close();
			}
			catch (IOException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			break;
		}

		default:
			break;
		}

		return null;
	}

	@Override
	public void onClick(View v)
	{
		switch (v.getId())
		{
		case R.id.trans_avter_btn_back:
			this.finish();

			break;

		case R.id.voice_trans_save:
		{

			tonggleMenu();
			break;
		}
		case R.id.alert_menu_qq:
		{

			beforeShareQQ();
			break;
		}
		case R.id.alert_menu_sendtofriend:
		{

			SharedPreferences sp = this.getSharedPreferences(
					MainActivity.SP_USR_LOGIN_STATUS,
					Activity.MODE_MULTI_PROCESS);

			boolean isUserLog = sp.getBoolean(MainActivity.LOGIN_STATUE, false);

			if (isUserLog)
			{
				Intent intent = new Intent(this, NewSendToFriendsActivity.class);
				intent.putExtra(NewSendToFriendsActivity.EMAIL_CONTET,
						this.mContentTextView.getText().toString());

				startActivity(intent);
			}
			else
			{
				Toast.makeText(this, "您还没有登录，请先登录！", Toast.LENGTH_LONG).show();
			}

			break;
		}
		case R.id.alert_menu_save:
		{
			saveContent();
			break;
		}

		case R.id.alert_menu_check:
		{

			Map<String, Object> pa = new HashMap<String, Object>();
			pa.put(MainServiceKey.CHECK_CONTENT, this.mContentTextView
					.getText().toString());
			MainServiceTask mstMainServiceTask = new MainServiceTask(
					TaskType.CHECK_SPELL, pa, this.getClass().getName()
							.toString());
			MainService.addActivityMap(VoiceAfterTransActivity.class.getName(),
					this);
			MainService.addTaskQueue(mstMainServiceTask);
			mProgressDialog.setMessage("正在为您拼命校验中~");
			mProgressDialog.show();

			tonggleMenu();
		}

		default:
			break;
		}

	}

	private void beforeShareQQ()
	{

		Map<String, Object> paras = new HashMap<String, Object>();
		paras.put(MainServiceKey.BEFORE_SHARE_QQ_CONTENT, mContentTextView
				.getText().toString());

		MainServiceTask msg = new MainServiceTask(TaskType.BEFORE_SHARE_QQ,
				paras, this.getClass().getName());

		MainService.addActivityMap(this.getClass().getName(), this);

		MainService.addTaskQueue(msg);

	}

	private void tonggleMenu()
	{

		if (alertMenu.getVisibility() == View.VISIBLE)
		{
			alertMenu.setVisibility(View.GONE);
		}
		else
		{
			alertMenu.setVisibility(View.VISIBLE);
		}
	}

	private void saveContent()
	{
		try
		{
			// BufferedWriter bw = new BufferedWriter(new FileWriter(
			// file.getName().split("\\.")[0] + ".txt"));
			BufferedWriter bw = new BufferedWriter(new FileWriter(new File(
					Sound.DIR + fileName.split("\\.")[0] + ".vtf")));
			bw.write(this.mContentTextView.getText().toString());
			bw.flush();
			bw.close();
			Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show();

		}
		catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
			Toast.makeText(this, "文件保存出现异常", Toast.LENGTH_SHORT).show();
		}
	}

	private SpannableStringBuilder jsonBuilder(String reString)
	{
		SpannableStringBuilder builder = new SpannableStringBuilder();
		try
		{
			JSONArray jsonArray = new JSONArray(reString);

			JSONObject jo = null;
			int length = jsonArray.length();

			for (int i = 0; i < length; i++)
			{

				jo = new JSONObject(jsonArray.get(i).toString());
				String srcWord = jo.getString("s");
				String followWords = jo.getString("f");

				if (followWords != null && followWords.equals("null") == false)
				{// 当存在候选集合时候

					int tempS = builder.length();
					int tempE = tempS + srcWord.length();
					builder.append(srcWord);
					builder.setSpan(new ForegroundColorSpan(Color.RED), tempS,
							tempE, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
					tempS = builder.length();
					tempE = tempS + followWords.length();
					builder.append(followWords);
					builder.setSpan(new ForegroundColorSpan(Color.BLUE), tempS,
							tempE, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				}
				else
				{
					builder.append(srcWord);
				}

			}
			return builder;

		}
		catch (JSONException e1)
		{
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		return builder;
	}

	@Override
	public void onCancel()
	{
		// TODO Auto-generated method stub

	}

	@Override
	public void onComplete(Object arg0)
	{
		// TODO Auto-generated method stub

	}

	@Override
	public void onError(UiError arg0)
	{
		// TODO Auto-generated method stub

	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		if (null != QQ)
			QQ.onActivityResult(requestCode, resultCode, data);
	}
}
